<template>
  <div>
    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="dialogFormVisible"
      :before-close="close"
      :title="title"
      width="800px"
      :top="'10vh'"
    >
      <el-form ref="form" :model="form" size="small" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item
              label="文件"
              prop="url"
              :rules="[
                { required: true, message: '请上传附件', trigger: 'change' }
              ]"
            >
              <el-upload
                class="upload-demo"
                :action="
                  baseUrl + 'rest/api/config/v1/file/custom/upload?type=9&fs=1'
                "
                :headers="customHeader"
                :on-remove="handleRemove"
                :on-success="handleSuccess"
                :before-remove="beforeRemove"
                :before-upload="beforeUpload"
                multiple
                :limit="1"
                accept=".xls,.xlsx,.doc,.docx,.zip,.jpg,.png,.pdf"
                :file-list="fileList"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">
                  只能上传.xls,.xlsx,.doc,.docx,.pdf，文件大小不超过10Mb，替换新文件前，请删除老文件后上传！
                </div>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="文件名称"
              prop="fileName"
              :rules="[
                {
                  required: true,
                  message: '请输入资源文件名称',
                  trigger: 'blur'
                }
              ]"
              style="width: 100%"
            >
              <el-input v-model="form.fileName" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-select
              v-model="form.type"
              placeholder="请选择资源类型"
              style="width: 200px"
            >
              <el-option
                v-for="item in dict.zy_type"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-col>
          <el-col :span="24">
            <el-form-item
              label="主管部门"
              prop="organization.id"
              :rules="[
                {
                  required: true,
                  message: '主管部门不能为空',
                  trigger: 'change'
                }
              ]"
            >
              <tree-select
                v-model="form.organization.id"
                :options="depts"
                :load-options="loadDepts"
                style="width: 200px"
                placeholder="选择部门"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否游客可见">
              <el-radio-group v-model="form.sfkf">
                <el-radio
                  v-for="item in status"
                  :key="item.id"
                  :label="item.value"
                >{{ item.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="px" style="width: 100%">
              <el-input-number v-model="form.px" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="close">取消</el-button>
        <el-button
          :loading="loading"
          type="primary"
          @click="save('form')"
        >确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getToken } from '@/utils/auth'
import { saveObject, updateObject } from '@/api/resource/index'
import TreeSelect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'
import { getDepts, getDeptSuperior } from '@/api/system/dept'
export default {
  name: 'ManagerResourcesEntity',
  components: { TreeSelect },
  dicts: ['zy_type'],
  data() {
    return {
      customHeader: { APEXEDU: getToken() },
      fileList: [],
      dialogFormVisible: false,
      baseUrl: process.env.VUE_APP_BASE_API,
      title: '资源管理',
      loading: false,
      depts: [],
      status: [
        { id: 0, value: false, label: '否' },
        { id: 1, value: true, label: '是' }
      ],
      form: {
        id: null,
        fileName: null,
        type: '',
        organization: {
          id: null
        },
        sfkf: true,
        sfsc: false,
        ext: '',
        size: '',
        path: '',
        newName: '',
        url: '',
        px: 0
      },
      queryData: null
    }
  },
  methods: {
    beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 10
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过10MB!')
      }
      return isLt2M
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    handleSuccess(response, file, fileList) {
      if (fileList === null || fileList.length === 0) {
        this.form.url = ''
        this.form.ext = ''
        this.form.path = ''
        this.form.size = ''
        this.form.newName = ''
      } else {
        const lists = fileList.map(item => {
          if (undefined !== item.response) {
            return {
              fileName: item.response.data.name,
              id: item.response.data.id,
              url: item.response.data.url,
              suffix: item.response.data.ext,
              path: item.response.data.path,
              size: item.response.data.size
            }
          } else {
            return {
              fileName: item.fileName,
              id: item.id,
              url: item.url,
              path: item.path,
              size: item.size,
              suffix: item.suffix
            }
          }
        })
        this.form.newName = lists[0].fileName
        this.form.fileName = lists[0].fileName
        this.form.url = lists[0].url
        this.form.ext = lists[0].suffix
        this.form.path = lists[0].path
        this.form.size = lists[0].size
      }
    },
    handleRemove(file, fileList) {
      if (fileList === null || fileList.length === 0) {
        this.form.url = ''
        this.form.ext = ''
        this.form.path = ''
        this.form.size = ''
        this.form.newName = ''
      } else {
        this.form.url = ''
        this.form.ext = ''
        this.form.path = ''
        this.form.size = ''
        this.form.newName = ''
      }
    },
    handleUploadSuccess(data) {
      this.form.backImage = data.url
      this.dialogTableVisible = false
    },
    schoolBackgroundImage() {
      this.cropperName = 'handleUploadBackgroundSuccess'
      this.dialogTableVisible = true
    },
    getDeptParent() {
      getDepts({ enabled: true }).then(res => {
        this.depts = res.content.map(function(obj) {
          if (obj.hasChildren) {
            obj.children = null
          }
          return obj
        })
      })
    },
    getSupDepts(deptId) {
      getDeptSuperior(deptId).then(res => {
        const date = res.content
        this.buildDepts(date)
        this.depts = date
      })
    },
    buildDepts(depts) {
      depts.forEach(data => {
        if (data.children) {
          this.buildDepts(data.children)
        }
        if (data.hasChildren && !data.children) {
          data.children = null
        }
      })
    },
    loadDepts({ action, parentNode, callback }) {
      if (action === LOAD_CHILDREN_OPTIONS) {
        getDepts({ enabled: true, pid: parentNode.id }).then(res => {
          const { content } = res
          parentNode.children = content.map(function(obj) {
            if (obj.hasChildren) {
              obj.children = null
            }
            return obj
          })
          setTimeout(() => {
            callback()
          }, 200)
        })
      }
    },
    selected(name) {
      this.form.icon = name.url
    },
    openEntity(data) {
      if (undefined !== data && undefined !== data.id && data.id !== null) {
        console.log(data)
        this.form = Object.assign({}, data)
        this.title = '修改资源信息'
        const file = {
          name: data.newName,
          id: data.id,
          url: data.url,
          path: data.path,
          size: data.size,
          suffix: data.ext
        }
        this.fileList = []
        this.fileList.push(file)
        this.getSupDepts(data.organization.id)
        this.dialogFormVisible = true
      } else {
        this.title = '新增资源信息'
        this.getDeptParent()
        this.dialogFormVisible = true
      }
    },
    save(formName) {
      this.loading = true
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.form.id !== null && undefined !== this.form.id) {
            updateObject(this.form)
              .then(res => {
                this.$message.success('更新成功！')
                this.close()
              })
              .catch(() => {
                this.loading = false
                this.$message.error('更新失败！')
              })
          } else {
            saveObject(this.form)
              .then(res => {
                this.$message.success('保存成功！')
                this.close()
                this.loading = false
              })
              .catch(() => {
                this.loading = false
                this.$message.error('保存失败！')
              })
          }
        } else {
          this.loading = false
          console.log('error submit!!')
          return false
        }
      })
    },
    close() {
      this.loading = false
      this.fileList = []
      Object.assign(this.$data.form, this.$options.data.call(this).form)
      this.$refs['form'].resetFields()
      this.dialogFormVisible = false
      this.$emit('fetch-data')
    }
  }
}
</script>

<style scoped>
.schoolBottomImage {
  width: 100%;
  height: 250px;
  border: 1px dashed #9b9b9b;
  border-radius: 4px;
  text-align: center;
  line-height: 250px;
  font-size: 34px;
}
.school-bak-image {
  width: 100%;
  height: 100%;
}
</style>
